//
//  AutoViewController.m
//  Light
//
//  Created by 骁唐 on 15/8/27.
//  Copyright (c) 2015年 骁唐. All rights reserved.
//

#import "AutoViewController.h"
#import "AppDelegate.h"
#import "UserConfig.h"
@interface AutoViewController ()<UIPickerViewDataSource,UIPickerViewDelegate,UIGestureRecognizerDelegate>
@property (weak, nonatomic) IBOutlet UIImageView *backGround;
//星期Button
@property (weak, nonatomic) IBOutlet UIButton *Sunday;
@property (weak, nonatomic) IBOutlet UIButton *Monday;
@property (weak, nonatomic) IBOutlet UIButton *Tuesday;
@property (weak, nonatomic) IBOutlet UIButton *Wednesday;
@property (weak, nonatomic) IBOutlet UIButton *Thursday;
@property (weak, nonatomic) IBOutlet UIButton *Friday;
@property (weak, nonatomic) IBOutlet UIButton *Saturday;
//星期写入

//分钟Buton
@property (weak, nonatomic) IBOutlet UIButton *threeMinBtn;
@property (weak, nonatomic) IBOutlet UIButton *fiveMinBtn;
@property (weak, nonatomic) IBOutlet UIButton *tenMinBtn;
@property (weak, nonatomic) IBOutlet UIButton *fifteenMinBtn;
@property (weak, nonatomic) IBOutlet UIButton *thirtyMinBtn;
@property int myMinute;

@property (weak, nonatomic) IBOutlet UIPickerView *myPikerView;
@property (strong,nonatomic) NSMutableArray *hourArray;
@property (strong,nonatomic) NSMutableArray *minuteArray;

//蓝牙传值
@property(nonatomic,strong)CBCharacteristic *writeCharacteristic;
@property(nonatomic,strong)CBPeripheral *myPeripheral;

//距离当前时间Label
@property (weak, nonatomic) IBOutlet UILabel *hourLabel;
@property (weak, nonatomic) IBOutlet UILabel *minuteLabel;
//当前时间
@property (assign,nonatomic) int currentHour;
@property (assign,nonatomic) int currentMin;
//设置时间
@property (assign,nonatomic) int setHour;//时
@property (assign,nonatomic) int setMin;//分
//差距时间
@property (assign,nonatomic) int gapHour;
@property (assign,nonatomic) int gapMin;
//小憩
@property (copy,nonatomic) NSString *currentXiaoQiMark;
@end

@implementation AutoViewController
{
    NSString *hourRow;//时(string)
    NSString *minRow;//分钟(string)
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationController.interactivePopGestureRecognizer.delegate = self;//设置delegate
    self.navigationController.interactivePopGestureRecognizer.enabled = YES;//打开滑动
    // Do any additional setup after loading the view.
    AppDelegate *delegate = [[UIApplication sharedApplication]delegate];
    _writeCharacteristic = delegate.writeCharacteristic;
    _myPeripheral = delegate.peripheral;
    //初始化小憩MARK（String）
    self.currentXiaoQiMark = delegate.xiaoqiMark;
    self.hourArray = [[NSMutableArray alloc] init];
    for  (int i = 0; i<= 23; i++)
    {//小时
        if (i<10)
        {//10以下，需要在前面补0
            [self.hourArray addObject:[NSString stringWithFormat:@"0%d",i]];
        }
        else
        {
            [self.hourArray addObject:[NSString stringWithFormat:@"%d",i]];
        }
    }
    self.minuteArray = [[NSMutableArray alloc] init];
    for (int i = 0; i <= 59; i++)
    {//分钟
        if (i <10 )
        {
            [self.minuteArray addObject:[NSString stringWithFormat:@"0%d",i]];
        }else
        {
            [self.minuteArray addObject:[NSString stringWithFormat:@"%d",i]];
        }
       
    }
    _Wednesday.highlighted = NO;//周三button的highlighted
    NSDate *  senddate=[NSDate date];//获取当前系统时间
    NSDateFormatter  *dateformatter=[[NSDateFormatter alloc] init];
    [dateformatter setDateFormat:@"HHmm"];
    NSString *  currenTime=[dateformatter stringFromDate:senddate];
    TJJLog(@"系统时间%@",currenTime);
    int currentHour = [[currenTime substringWithRange:NSMakeRange(0, 2)] intValue];
    int currentMinute = [[currenTime substringWithRange:NSMakeRange(2, 2)] intValue];
    TJJLog(@"系统小时%d",currentHour);
    TJJLog(@"系统分钟%d",currentMinute);
    int HourSec1 =  currentHour*3600;
    int MinuteSec1 =currentMinute*60;
    int currentSec = HourSec1 + MinuteSec1;//当前的时+分
    
    int myCurrentSec = 86400;//一天的秒数
    int gapSec;//
    if (myCurrentSec > currentSec)
    {
        gapSec = abs(myCurrentSec - currentSec);
    }
    else
    {
        gapSec = 86400 - currentSec + myCurrentSec;
    }
    //    int gapSec = abs(myCurrentSec - currentSec);
    TJJLog(@"相差秒数%d",gapSec);
    self.gapHour = gapSec/3600;
    self.gapMin = gapSec/60 - gapSec/3600*60;
    self.hourLabel.text = [[NSString alloc] initWithFormat:@"%d",self.gapHour];
    self.minuteLabel.text = [[NSString alloc] initWithFormat:@"%d",self.gapMin ];


    //Sunday Monday Tuesday Wednesday Thursday Friday Saturday
    UserConfig *config = [UserConfig sharingUserConfig];
    //下面的配置全部改成YES,本来是yes 下面是no
    int Sunday;
    Sunday = [[config getSundayMark] intValue];
    if (Sunday == 1) {
        self.Sunday.selected = YES;
    }else
    {
        self.Sunday.selected = YES;
    }
    
    int Monday;
    Monday = [[config getMondayMark] intValue];
    if (Monday == 1) {
        self.Monday.selected = YES;
    }else
    {
        self.Monday.selected = YES;
    }
    
    int Tuesday;
    Tuesday = [[config getTuesdayMark] intValue];
    if (Tuesday == 1) {
        self.Tuesday.selected = YES;
    }else
    {
        self.Tuesday.selected = YES;
    }
    
    int Wednesday;
    Wednesday = [[config getWednesdayMark] intValue];
    if (Wednesday == 1) {
        self.Wednesday.selected = YES;
    }else
    {
        self.Wednesday.selected = YES;
    }
    
    int Thursday;
    Thursday = [[config getThursdayMark] intValue];
    if (Thursday == 1) {
        self.Thursday.selected = YES;
    }else
    {
        self.Thursday.selected = YES;
    }
    
    int Friday;
    Friday = [[config getFridayMark] intValue];
    if (Friday == 1) {
        self.Friday.selected = YES;
    }else
    {
        self.Friday.selected = YES;
    }
    
    int Saturday;
    Saturday = [[config getSaturdayMark] intValue];
    if (Saturday == 1) {
        self.Saturday.selected = YES;
    }else
    {
        self.Saturday.selected = YES;
    }
    
    if   ([[delegate.xiaoqiMark substringWithRange:NSMakeRange(0, 1)] isEqualToString:@"1"])
    {
        self.threeMinBtn.selected = YES;
        self.myMinute +=3;
    }else
    {
        self.threeMinBtn.selected = NO;
    }
    if   ([[delegate.xiaoqiMark substringWithRange:NSMakeRange(1, 1)] isEqualToString:@"2"])
    {
        self.fiveMinBtn.selected = YES;
        self.myMinute +=5;
    }else
    {
        self.fiveMinBtn.selected = NO;
    }
    if   ([[delegate.xiaoqiMark substringWithRange:NSMakeRange(2, 1)] isEqualToString:@"3"])
    {
        self.tenMinBtn.selected = YES;
        self.myMinute +=10;
    }else
    {
        self.tenMinBtn.selected = NO;
    }
    if   ([[delegate.xiaoqiMark substringWithRange:NSMakeRange(3, 1)] isEqualToString:@"4"])
    {
        self.fifteenMinBtn .selected = YES;
        self.myMinute +=15;
    }else
    {
        self.fifteenMinBtn.selected = NO;
    }
    if   ([[delegate.xiaoqiMark substringWithRange:NSMakeRange(4, 1)] isEqualToString:@"5"])
    {
        self.thirtyMinBtn.selected = YES;
        self.myMinute +=30;
    }else
    {
        self.thirtyMinBtn.selected = NO;
    }
    TJJLog(@"用户保存数据中的设置分钟数%d",self.myMinute);
    hourRow = [config getCUrrentAutoHourRow];//从用户保存的数据中获取-当前时
    minRow = [config getCurrentAutoMinRow];//从用户保存的数据中获取-当前分钟
    //设置默认在compoent列中默认选中row行  （时间滚轮选择器---场景保留）
    [self.myPikerView selectRow:[[config getCUrrentAutoHourRow] intValue] inComponent:0 animated:YES];
    [self.myPikerView selectRow:[[config getCurrentAutoMinRow] intValue] inComponent:2 animated:YES];
    
    self.setHour = [hourRow intValue];
    self.setMin = [minRow intValue];
    //获取当前系统时间
    NSDate *  senddate1 =[NSDate date];
    NSDateFormatter  *dateformatter1=[[NSDateFormatter alloc] init];
    [dateformatter1 setDateFormat:@"HHmm"];
    NSString *  currenTime1=[dateformatter stringFromDate:senddate1];
    TJJLog(@"系统时间%@",currenTime1);
    int currentHour1 = [[currenTime1 substringWithRange:NSMakeRange(0, 2)] intValue];
    int currentMinute1 = [[currenTime1 substringWithRange:NSMakeRange(2, 2)] intValue];
    TJJLog(@"系统小时%d",currentHour1);
    TJJLog(@"系统分钟%d",currentMinute1);
    int HourSec11 =  currentHour1*3600;
    int MinuteSec11 =currentMinute1*60;
    int currentSec1 = HourSec11 + MinuteSec11;
    TJJLog(@"设定小时%d,设定分钟%d",self.setHour,self.setMin);
    int myCurrentSec1 = self.setHour*3600 + self.setMin*60;
    int gapSec1;
    if (myCurrentSec1 > currentSec1)
    {
        gapSec1 = abs(myCurrentSec1 - currentSec1);
        
    }else
    {
        gapSec1 = 86400 - currentSec1 + myCurrentSec1;
    }
    //    int gapSec = abs(myCurrentSec - currentSec);
    TJJLog(@"相差秒数%d",gapSec1);
    self.gapHour = gapSec1/3600;
    self.gapMin = gapSec1/60 - gapSec1/3600*60;
    self.hourLabel.text = [[NSString alloc] initWithFormat:@"%d",self.gapHour];
    self.minuteLabel.text = [[NSString alloc] initWithFormat:@"%d",self.gapMin];
    
}

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer {
    return  YES;
}
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldBeRequiredToFailByGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer {
    return [gestureRecognizer isKindOfClass:UIScreenEdgePanGestureRecognizer.class];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
-(NSInteger) numberOfComponentsInPickerView:(UIPickerView *)pickerView{
   // TJJLog(@"调用%s ,%d",__FUNCTION__,__LINE__);
    //返回有几列 ，注意
    return 3;
}

#pragma mark -
#pragma mark 返回指定列的行数
- (NSInteger) pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{
  //  TJJLog(@"调用%s ,%d",__FUNCTION__,__LINE__);
    if (component==0) {
        return  [self.hourArray count];
    } else if(component==1){
        
        return  1;
    }
    else if(component==2){
        return [self.minuteArray count];
        
    }else if(component==3){
        return 1;
    }
    return 0;
}

//以下是代理部分，可以自定义视图
#pragma mark -
#pragma mark 返回指定列，行的高度，就是自定义行的高度
- (CGFloat)pickerView:(UIPickerView *)pickerView rowHeightForComponent:(NSInteger)component{
  //  TJJLog(@"调用%s ,%d",__FUNCTION__,__LINE__);
    return  54;
}
#pragma mark -
#pragma mark 返回指定列的宽度
- (CGFloat) pickerView:(UIPickerView *)pickerView widthForComponent:(NSInteger)component{
    return 40;
}

- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view{
  //  TJJLog(@"调用%s ,%d",__FUNCTION__,__LINE__);
    //思想就是：先创建一个View以指定列的宽度，和所在列行的高度，为尺寸
    //再建立一个label,在这个view上显示字体，字体颜色，字体大小，然后，把这个label添加到view中
    //返回view，作为指定列的每行的视图
    //取得指定列的宽度
    CGFloat width=[self pickerView:pickerView widthForComponent:component];
    //取得指定列，行的高度
    CGFloat height=[self pickerView:pickerView rowHeightForComponent:component];
    //定义一个视图
    UIView *myView=[[UIView alloc] init];
    //指定视图frame
    myView.frame=CGRectMake(0, 0, width, height);
    UILabel *labelOnComponent=[[UILabel alloc] init];
    labelOnComponent.frame=myView.frame;
    //    labelOnComponent.tag=200;
    
    if (component==0) {
        //如果是第0列
        labelOnComponent.text= [self.hourArray objectAtIndex:row];
        labelOnComponent.textColor = [UIColor whiteColor];
        labelOnComponent.textAlignment = UIBaselineAdjustmentAlignCenters;
        [labelOnComponent setNumberOfLines:0];
        labelOnComponent.font = [UIFont fontWithName:@"Helvetica" size:35];
        labelOnComponent.adjustsFontSizeToFitWidth = YES;
    }
    else if(component==1){
        //如果是第1列
        //以说选择行为索引，取得颜色数组中的颜色，并把label的背景色设为该颜色
        labelOnComponent.text = @":";
        labelOnComponent.textColor = [UIColor whiteColor];
        labelOnComponent.textAlignment = UIBaselineAdjustmentAlignCenters;
        [labelOnComponent setNumberOfLines:0];
        labelOnComponent.font = [UIFont fontWithName:@"Helvetica" size:35];
        labelOnComponent.adjustsFontSizeToFitWidth = YES;
    }
    else if(component==2){
        //如果是第2列
        //label 上显示的是相应字体
        labelOnComponent.text= [self.minuteArray objectAtIndex:row];
        labelOnComponent.textColor = [UIColor whiteColor];
        labelOnComponent.textAlignment = UIBaselineAdjustmentAlignCenters;
        [labelOnComponent setNumberOfLines:0];
        labelOnComponent.font = [UIFont fontWithName:@"Helvetica" size:35];
        labelOnComponent.adjustsFontSizeToFitWidth = YES;
    }
    [myView addSubview:labelOnComponent];
    return myView;
}

#pragma mark -
#pragma mark 点击选中滚轮选择时间
- (void)pickerView:(UIPickerView *)pickerView
      didSelectRow:(NSInteger)row
       inComponent:(NSInteger)component
{
    if (component == 0)
    {
        //获取当前时间
        //setHour 设置的时间
        self.setHour = [self.hourArray[row] intValue];//设置时（int）
        hourRow = [[NSString alloc] initWithFormat:@"%d",(int)row];//设置选中的时（String类型）
    }
    else if (component == 2)
    {
        self.setMin = [self.minuteArray[row] intValue];//设置分钟(int)
        minRow = [[NSString alloc] initWithFormat:@"%d",(int)row];//设置选中的分钟（String类型）
    }
    //获取当前系统时间
    NSDate *  senddate=[NSDate date];
    NSDateFormatter  *dateformatter=[[NSDateFormatter alloc] init];
    [dateformatter setDateFormat:@"HHmm"];
    NSString *  currenTime=[dateformatter stringFromDate:senddate];
    TJJLog(@"系统时间%@",currenTime);
    int currentHour = [[currenTime substringWithRange:NSMakeRange(0, 2)] intValue];
    int currentMinute = [[currenTime substringWithRange:NSMakeRange(2, 2)] intValue];
    TJJLog(@"系统小时%d",currentHour);
    TJJLog(@"系统分钟%d",currentMinute);
    int HourSec1 =  currentHour*3600;
    int MinuteSec1 =currentMinute*60;
    int currentSec = HourSec1 + MinuteSec1;
    TJJLog(@"设定小时%d,设定分钟%d",self.setHour,self.setMin);
    int myCurrentSec = self.setHour*3600 + self.setMin*60;
    int gapSec;
    if (myCurrentSec > currentSec)
    {
         gapSec = abs(myCurrentSec - currentSec);
        
    }else
    {
       gapSec = 86400 - currentSec + myCurrentSec;
    }
//    int gapSec = abs(myCurrentSec - currentSec);
    TJJLog(@"相差秒数%d",gapSec);
    self.gapHour = gapSec/3600;
    self.gapMin = gapSec/60 - gapSec/3600*60;
    self.hourLabel.text = [[NSString alloc] initWithFormat:@"%d",self.gapHour];
    self.minuteLabel.text = [[NSString alloc] initWithFormat:@"%d",self.gapMin ];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/
#pragma mark -
#pragma mark 导航返回
- (IBAction)backClick {
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark -
#pragma mark 星期日btnClick
- (IBAction)SundayClick{
    TJJLog(@"周日");
    _Sunday.selected = !_Sunday.selected;
}

#pragma mark -
#pragma mark 星期一btnClick
- (IBAction)MondayClick {
    TJJLog(@"周一");
    _Monday.selected = !_Monday.selected;
}

#pragma mark -
#pragma mark 星期二btnClick
- (IBAction)TuesdayClick {
    TJJLog(@"周二");
    _Tuesday.selected = !_Tuesday.selected;
}

#pragma mark -
#pragma mark 星期三btnClick
- (IBAction)WednesdayClick {
    TJJLog(@"周三");
    _Wednesday.selected = !_Wednesday.selected;
}

#pragma mark -
#pragma mark 星期四btnClick
- (IBAction)ThursdayClick {
    TJJLog(@"周四点击");
    _Thursday.selected = !_Thursday.selected;
}

#pragma mark -
#pragma mark 星期五btnClick
- (IBAction)FridayClick {
    TJJLog(@"周五");
    _Friday.selected = !_Friday.selected;
}

#pragma mark -
#pragma mark 星期六btnClick
- (IBAction)SaturdayClick {
    TJJLog(@"周六");
    _Saturday.selected = !_Saturday.selected;
}

#pragma mark -
#pragma mark 设置智能唤醒1
-(void)weekWrite
{
    AppDelegate *delegate = [[UIApplication sharedApplication] delegate];
    int week = 0;//星期数二进制字符串转换成的10进制数；默认全未选中
    if(_Monday.selected == YES){
        week = week|1;
    }
    if(_Tuesday.selected == YES){
        week = week|2;
    }
    if(_Wednesday.selected == YES){
        week = week|4;
    }
    if(_Thursday.selected == YES){
        week = week|8;
    }
    if(_Friday.selected == YES){
        week = week|16;
    }
    if(_Saturday.selected == YES){
        week = week|32;
    }
    if(_Sunday.selected  == YES){
        week = week|64;
    }
    if (week != 0)
    {
        Byte byt7[7] = {0};
        byt7[0] = 0xAE;
        byt7[1] = 0x04;
        byt7[2] = 0x40;
        byt7[3] = week;//设置星期
        byt7[4] = ((self.setHour/10)<<4)|(self.setHour%10);
        byt7[5] = ((self.setMin/10)<<4)|(self.setMin%10);
    //    NSInteger lastMinute = (minute/10)*16+minute%10;
    //    NSInteger lastHour = (myHour/10)*16+myHour%10;
        byt7[6] = 0xAA;
        TJJLog(@"%s",byt7);
        NSData *data = [NSData dataWithBytes:&byt7 length:sizeof(byt7)];
        if ([delegate.writeCharacteristic.UUID.UUIDString isEqual:@"FFF2"]) {
            [self.myPeripheral writeValue:data
                        forCharacteristic:delegate.writeCharacteristic
                                     type:CBCharacteristicWriteWithResponse];
        }
        NSDate *date = [NSDate date];
        NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
        NSDateComponents *comps = [[NSDateComponents alloc] init];
        NSInteger unitFlags = NSYearCalendarUnit |
        NSMonthCalendarUnit |
        NSDayCalendarUnit |
        NSWeekdayCalendarUnit |
        NSHourCalendarUnit |
        NSMinuteCalendarUnit |
        NSSecondCalendarUnit;
        comps = [calendar components:unitFlags fromDate:date];
        NSTimeInterval settime = [[NSDate date] timeIntervalSince1970];
        int nowsecond  = (int)[comps hour]*3600+(int)[comps minute]*60+(int)[comps second];
        UserConfig *config = [UserConfig sharingUserConfig];
        [config setStartalarmTime:@(settime)];
        if (nowsecond>=self.setHour*3600+self.setMin*60)
            [config setTodayAlarmClockCarryOutMark:@"1"];
        else [config setTodayAlarmClockCarryOutMark:@"0"];
        NSNumber *autoTime = @(self.setHour*3600+self.setMin*60); //设置重复闹钟相对于0点的时间。
        TJJLog(@"自然唤醒的时间：%@",autoTime);
        [config setAutoTime:autoTime];
        TJJLog(@"重复-4------------------%@",data);
        
        delegate.alertAutoOne = [[UIAlertView alloc] initWithTitle:nil message:ALERT_MESSAGE_AUTO_ONE_ON delegate:self cancelButtonTitle:nil otherButtonTitles:nil, nil];
        [delegate.alertAutoOne show];
        //0.8S隐藏
        [self performSelector:@selector(closeAlertViewOne) withObject:nil afterDelay:1];
        
    }
    else
    {//如果一个都没选，关闭自然唤醒1
        NSData *data = [TJJ_SD_BLE_INSTRUCTIONS writeString:SD_SEND_AUTOEND_ONE];
        if ([delegate.writeCharacteristic.UUID.UUIDString isEqual:@"FFF2"]) {
            [self.myPeripheral writeValue:data
                        forCharacteristic:delegate.writeCharacteristic
                                     type:CBCharacteristicWriteWithResponse];
        }
        delegate.alertAutoOne = [[UIAlertView alloc] initWithTitle:nil message:ALERT_MESSAGE_AUTO_ONE_OFF delegate:self cancelButtonTitle:nil otherButtonTitles:nil, nil];
        [delegate.alertAutoOne show];
        //0.8S隐藏
        [self performSelector:@selector(closeAlertViewOne) withObject:nil afterDelay:1];
    }
    [self performSelector:@selector(setCurrentMinute) withObject:nil afterDelay:1.2];//设置自然唤醒2
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark -
#pragma mark 开始智能唤醒2（小憩）
- (void)setCurrentMinute
{
    TJJLog(@" 开始智能唤醒2（小憩）");
    //设置分钟
    NSDate *date = [NSDate date];
    NSTimeInterval currenttime = [[NSDate date] timeIntervalSince1970];
    while (currenttime<=0) {
        currenttime = [[NSDate date] timeIntervalSince1970];
    }
    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    NSDateComponents *comps = [[NSDateComponents alloc] init];
    NSInteger unitFlags = NSYearCalendarUnit |
    NSMonthCalendarUnit |
    NSDayCalendarUnit |
    NSWeekdayCalendarUnit |
    NSHourCalendarUnit |
    NSMinuteCalendarUnit |
    NSSecondCalendarUnit;
    comps = [calendar components:unitFlags fromDate:date];
    NSInteger myHour ;
    NSInteger minute ;
    NSInteger sumSec;
    NSInteger mySec;
    sumSec = ([comps hour] * 3600) + ([comps minute] * 60)  + (self.myMinute * 60);
    myHour = sumSec/ 3600;
    minute = sumSec%3600/60;
    mySec = sumSec%3600%60;
    NSInteger lastMinute = (minute/10)*16+minute%10;
    NSInteger lastHour = (myHour/10)*16+myHour%10;
    //
    //    NSString *lastTime = [[NSString alloc] initWithFormat:@"%ld%ld",(long)myHour,(long)minute];
    AppDelegate *delegate = [[UIApplication sharedApplication] delegate];
    if (self.myMinute>0)
    {
        //NSString *lastTime = [[NSString alloc] initWithFormat:@"%lu",sumSec];
        long long int xiaoqitime = currenttime + (self.myMinute*60);
        delegate.xiaoqiTime = @(xiaoqitime);//设置小憩时间
        UserConfig *config = [UserConfig sharingUserConfig];
        [config setAutoXiaoQiTime:@(xiaoqitime)];//设置自动唤醒小憩时间
    
        Byte byt[6] = {0};
        byt[0] = 0xAE;
        byt[1] = 0x03;
        byt[2] = 0x41;//开始智能唤醒2
        byt[3] = lastHour;
        byt[4] = lastMinute;
        byt[5] = 0xAA;
        NSData *myData = [NSData dataWithBytes:&byt length:sizeof(byt)];
        if ([delegate.writeCharacteristic.UUID.UUIDString isEqual:@"FFF2"]) {
            [self.myPeripheral writeValue:myData
                        forCharacteristic:delegate.writeCharacteristic
                                     type:CBCharacteristicWriteWithResponse];//
        }
        TJJLog(@"分钟-----------------------%@",myData);
        
        delegate.alertAutoTwo = [[UIAlertView alloc] initWithTitle:nil message:[NSString stringWithFormat:@"%d%@",self.myMinute,ALERT_MESSAGE_AUTO_TWO_ON ] delegate:self cancelButtonTitle:nil otherButtonTitles:nil, nil];
        [delegate.alertAutoTwo show];
        //0.8S隐藏
        [self performSelector:@selector(closeAlertViewTwo) withObject:nil afterDelay:1];
    }
    else
    {//关闭小憩(自然唤醒2 关闭)
        NSData * data = [TJJ_SD_BLE_INSTRUCTIONS writeString:SD_SEND_AUTOEND_TWO];
        if ([delegate.writeCharacteristic.UUID.UUIDString isEqual:@"FFF2"]) {
            [self.myPeripheral writeValue:data
                        forCharacteristic:delegate.writeCharacteristic
                                     type:CBCharacteristicWriteWithResponse];//
        }
        delegate.alertAutoTwo = [[UIAlertView alloc] initWithTitle:nil message:ALERT_MESSAGE_AUTO_TWO_OFF delegate:self cancelButtonTitle:nil otherButtonTitles:nil, nil];
        [delegate.alertAutoTwo show];
        //0.8S隐藏
        [self performSelector:@selector(closeAlertViewTwo) withObject:nil afterDelay:1];
    }
}

#pragma mark -
#pragma mark 关闭弹窗TWO
- (void)closeAlertViewTwo
{
    AppDelegate * delegate = [[UIApplication sharedApplication] delegate];
    [delegate.alertAutoTwo dismissWithClickedButtonIndex:0 animated:YES];
}
#pragma mark -
#pragma mark 关闭弹窗One
- (void)closeAlertViewOne
{
    AppDelegate * delegate = [[UIApplication sharedApplication] delegate];
    [delegate.alertAutoOne dismissWithClickedButtonIndex:0 animated:YES];
}
#pragma mark 小憩时间（分钟选择）
#pragma mark -
#pragma mark 小憩3分钟
- (IBAction)threeMinClick {
    if(_threeMinBtn.selected)
    {
        _threeMinBtn.selected = NO;
      self.currentXiaoQiMark = [self.currentXiaoQiMark stringByReplacingOccurrencesOfString:@"1" withString:@"a"];
        self.myMinute -=3;
    }else
    {
        _threeMinBtn.selected = YES;
     self.currentXiaoQiMark =  [self.currentXiaoQiMark stringByReplacingOccurrencesOfString:@"a" withString:@"1"];
        self.myMinute +=3;
    }
}
#pragma mark -
#pragma mark 小憩5分钟
- (IBAction)fiveClick {
    if (_fiveMinBtn.selected) {
        _fiveMinBtn.selected = NO;
     self.currentXiaoQiMark =  [self.currentXiaoQiMark stringByReplacingOccurrencesOfString:@"2" withString:@"b"];
        self.myMinute -=5;
        
    }else
    {
        _fiveMinBtn.selected = YES;
      self.currentXiaoQiMark = [self.currentXiaoQiMark stringByReplacingOccurrencesOfString:@"b" withString:@"2"];
        self.myMinute +=5;
    }
}
#pragma mark -
#pragma mark 小憩10分钟
- (IBAction)tenMinClick {
    if (_tenMinBtn.selected) {
        _tenMinBtn.selected = NO;
     self.currentXiaoQiMark =  [self.currentXiaoQiMark stringByReplacingOccurrencesOfString:@"3" withString:@"c"];
        self.myMinute -=10;
    }
    else
    {
        _tenMinBtn.selected = YES;
       self.currentXiaoQiMark =[self.currentXiaoQiMark stringByReplacingOccurrencesOfString:@"c" withString:@"3"];
        self.myMinute +=10;
    }
}

#pragma mark -
#pragma mark 小憩15分钟
- (IBAction)fifteenClick {
    if (_fifteenMinBtn.selected) {
        _fifteenMinBtn.selected = NO;
     self.currentXiaoQiMark  = [self.currentXiaoQiMark stringByReplacingOccurrencesOfString:@"4" withString:@"d"];
        self.myMinute -=15;
    }else
    {
        _fifteenMinBtn.selected = YES;
     self.currentXiaoQiMark =  [self.currentXiaoQiMark stringByReplacingOccurrencesOfString:@"d" withString:@"4"];
        TJJLog(@"%d", self.myMinute);
        self.myMinute +=15;
    }
}
#pragma mark -
#pragma mark 小憩30分钟
- (IBAction)thirtyMinClick {
    if (_thirtyMinBtn.selected) {
        _thirtyMinBtn.selected = NO;
      self.currentXiaoQiMark = [self.currentXiaoQiMark stringByReplacingOccurrencesOfString:@"5" withString:@"e"];
        self.myMinute -=30;
    }else
    {
        _thirtyMinBtn.selected = YES;
      self.currentXiaoQiMark = [self.currentXiaoQiMark stringByReplacingOccurrencesOfString:@"e" withString:@"5"];
        self.myMinute +=30;
    }
}

#pragma mark -
#pragma mark 右上角确认按钮
- (IBAction)writeClick {
    [self weekWrite];//星期重复写入
    [self judgeWeekTodayAuto];//设置智能唤醒星期重复
    UserConfig *config = [UserConfig sharingUserConfig];
    NSNumber *autoTime = @(self.setHour*3600+self.setMin*60); //设置重复闹钟相对于0点的时间。
    TJJLog(@"自然唤醒的时间：%@",autoTime);
    [config setCurrentAutoHourRow:hourRow];
    [config setCurrentAutoMinRow:minRow];
    AppDelegate *delegate = [[UIApplication sharedApplication]delegate];
    delegate.currentAutoTime = autoTime;//设置自然唤醒的时间
    delegate.xiaoqiMark = self.currentXiaoQiMark;
    
    int weekmaskcode = (_Monday.selected) | (_Tuesday.selected<<1) |(_Wednesday.selected<<2)|(_Thursday.selected<<3)
    |(_Friday.selected<<4)|(_Saturday.selected<<5) | (_Sunday.selected<<6);
    
    [config setAlarmMask:@(weekmaskcode)];
    
    if (_Sunday.selected) {//星期天设置1
        [config setSundayMark:@"1"];
    }else
    {
        [config setSundayMark:@"0"];
    }
    
    if (_Monday.selected) {
        [config setMondayMark:@"1"];
    }else
    {
        [config setMondayMark:@"0"];
        
    }

    if (_Tuesday.selected) {
        [config setTuesdayMark:@"1"];
    }else
    {
        [config setTuesdayMark:@"0"];
    }
    
    if (_Wednesday.selected) {
        [config setWednesdayMark:@"1"];
    }else {
        [config setWednesdayMark:@"0"];
        
    }

    if (_Thursday.selected) {
        [config setThursdayMark:@"1"];
    }else
    {
        [config setThursdayMark:@"0"];
    }

    if (_Friday.selected) {
        [config setFridayMark:@"1"];
    }else
    {
        [config setFridayMark:@"0"];
    }
    
    if (_Saturday.selected) {
        [config setSaturdayMark:@"1"];;
    }else
    {
        [config setSaturdayMark:@"0"];
    }

}

#pragma mark -
#pragma mark viewWillAppear
-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    //强制竖屏
    [[UIDevice currentDevice] setValue:[NSNumber numberWithInteger:
                                        UIInterfaceOrientationPortrait]  forKey:@"orientation"];
    long long int currentTimeInt = [TJJDefines getTimeIntSince1970Current];
    if (currentTimeInt>=16200&& currentTimeInt <=34200) {
        self.backGround.image = [UIImage imageNamed:@"backgroundOne"];
    }else if (currentTimeInt>34200 && currentTimeInt<=55800)
    {
        self.backGround.image = [UIImage imageNamed:@"backgroundTwo"];
    }else if (currentTimeInt>55800 && currentTimeInt<=70200)
    {
        self.backGround.image = [UIImage imageNamed:@"backgroundThree"];
    }else if(currentTimeInt >70200 || currentTimeInt<16200)
    {
        self.backGround.image = [UIImage imageNamed:@"background_night"];
    }
}

#pragma mark -
#pragma mark 判断智能唤醒星期重复
- (void) judgeWeekTodayAuto
{
    NSDate *date = [NSDate date];
    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    NSDateComponents *comps = [[NSDateComponents alloc] init];
    NSInteger unitFlags = NSYearCalendarUnit |
    NSMonthCalendarUnit |
    NSDayCalendarUnit |
    NSWeekdayCalendarUnit |
    NSHourCalendarUnit |
    NSMinuteCalendarUnit |
    NSSecondCalendarUnit;
    comps = [calendar components:unitFlags fromDate:date];
    NSInteger week = [comps weekday];
    //Week:
    //    1 －－星期天
    //    2－－星期一
    //    3－－星期二
    //    4－－星期三
    //    5－－星期四
    //    6－－星期五
    //    7－－星期六
    NSInteger weekDay;
    
    switch (week) {
        case 1:
            weekDay = 7;
            break;
        case 2:
            weekDay = 1;
            break;
        case 3:
            weekDay = 2;
            break;
        case 4:
            weekDay = 3;
            break;
        case 5:
            weekDay = 4;
            break;
        case 6:
            weekDay = 5;
            break;
        case 7:
            weekDay = 6;
            break;
        default:
            break;
    }
    
    //Sunday Monday Tuesday Wednesday Thursday Friday Saturday
    UserConfig *config = [UserConfig sharingUserConfig];
    AppDelegate *delegate = [[UIApplication sharedApplication] delegate];
    
//    int myHour = (int)[comps hour];
//    int minute = (int)[comps minute];

//    int repeatSec = self.setHour * 3600 + self.setMin * 60;
//    int currentTime = myHour *3600 + minute *60;
    
    int weekmaskcode = (_Monday.selected) | (_Tuesday.selected<<1) |(_Wednesday.selected<<2)|(_Thursday.selected<<3)
    |(_Friday.selected<<4)|(_Saturday.selected<<5) | (_Sunday.selected<<6);
    
    [config setAlarmMask:@(weekmaskcode)];
    delegate.judgeAuto = (weekmaskcode!=0);
    
    
    if (_Sunday.selected) {
        [config setSundayMark:@"1"];
    }else
    {
        [config setSundayMark:@"0"];
    }
    
    if (_Monday.selected) {
        [config setMondayMark:@"1"];
    }else
    {
        [config setMondayMark:@"0"];
    }
    
    if (_Tuesday.selected) {
        [config setTuesdayMark:@"1"];
    }else
    {
        [config setTuesdayMark:@"0"];
    }
    
    if (_Wednesday.selected) {
        [config setWednesdayMark:@"1"];
    }else {
        [config setWednesdayMark:@"0"];
        
    }
    
    if (_Thursday.selected) {
        [config setThursdayMark:@"1"];
    }else
    {
        [config setThursdayMark:@"0"];
    }
    
    if (_Friday.selected) {
        [config setFridayMark:@"1"];
    }else
    {
        [config setFridayMark:@"0"];
    }
    
    if (_Saturday.selected) {
        [config setSaturdayMark:@"1"];;
    }else
    {
        [config setSaturdayMark:@"0"];
    }
}

@end
